package com.koron.css2.newProjectCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.newProjectCenter.bean.PjInfoBean;
import com.koron.css2.newProjectCenter.bean.PjTerminationBean;
import com.koron.css2.newProjectCenter.mapper.PjCollectionMapper;
import com.koron.css2.newProjectCenter.mapper.PjInfoMapper;
import com.koron.css2.newProjectCenter.mapper.PjTerminationMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.Date;

/**
 * 工程管理-单条工程终止信息新增
 * 1. settlement,comments,pjId,nodeCode 由前端传过来
 * 2. 返回id
 */
public class PjTerminationInsert implements ServerInterface {

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            PjTerminationBean pjTerminationBean = JsonUtils.objectToPojo(req.getData(),PjTerminationBean.class);
            PjTerminationMapper pjTerminationMapper = factory.getMapper(PjTerminationMapper.class);
            PjCollectionMapper pjCollectionMapper = factory.getMapper(PjCollectionMapper.class);
            PjInfoMapper pjInfoMapper = factory.getMapper(PjInfoMapper.class);
            PjInfoBean pjInfo = pjInfoMapper.selectById(pjTerminationBean.getPjId());
            if (pjCollectionMapper.processingCount(pjInfo.getBillNo()) > 0){
                return MessageBean.create(Constant.MESSAGE_INT_FAIL,"存在未收款的工程单据",null);
            }
            if (pjInfo.getDelayFlag() != null && 1 == pjInfo.getDelayFlag()){
                return MessageBean.create(Constant.MESSAGE_INT_FAIL,"该工程单处于延期状态中，暂不能申请终止",null);
            }
            if (pjInfo.getTerminationFlag() != null && 1 == pjInfo.getTerminationFlag()){
                return MessageBean.create(Constant.MESSAGE_INT_FAIL,"该工程单已处于终止审批流程中",null);
            }
            // 1. id,tenantId,createTime,createName,createAccount
            pjTerminationBean.setCreateInfo(userInfo);
            // 1.1 billNo,billDate
            pjTerminationBean.setBillNo(Tools.getBillNo(factory,"pj_termination"));
            pjTerminationBean.setBillDate(new Date());
            // 2. 插入数据
            pjTerminationMapper.insert(pjTerminationBean);
            // 3. 返回id
            MessageBean<String> messageBean = MessageBean.create(Constant.MESSAGE_INT_SUCCESS,"单条工程终止信息新增成功!",null);
            messageBean.setData(pjTerminationBean.getId());
            return messageBean;
        } catch (Exception e){
            logger.error("单条工程终止信息新增失败",e);
        }
        return MessageBean.create(Constant.MESSAGE_INT_FAIL,"单条工程终止信息新增失败",null);
    }
}
